package fons.navigator.export;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import com.google.common.collect.Maps;

public final class RenderingChain<R extends Renderer> {

	private Map<Class<?>, ElementRenderer<R>> renderers = Maps.newHashMap();
	private ElementRenderer<R> defaultRenderer;
			
	public void setNext (Class<?> type, ElementRenderer<R> renderer) {
		renderers.put(type, renderer);
	}
	
	public void setDefault (ElementRenderer<R> renderer) {
		this.defaultRenderer  = renderer;
	}
	
	public void render (R renderer, ExportableItem item) {
		
		ElementRenderer<R> r = renderers.get(item.getClass());
		if (r == null) {
			r = defaultRenderer;
		}
		
		if (r == null) {
			return;
		}
		
		try {
			Method method = r.getClass().getMethod("render", renderer.getClass(), item.getClass());
			method.invoke(r, renderer, item);
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
